package com.kitty.mina.filter;

import com.alibaba.fastjson.JSONObject;
import com.kitty.game.role.model.Role;
import com.kitty.game.enter.ReqMultiMoveTo;
import com.kitty.game.utils.JsonUtils;
import com.kitty.mina.MessageStatistics;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;
@Slf4j
public class MessageTraceFilter extends IoFilterAdapter {


    private boolean debug = true;

    @Override
    public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
        if (debug && traceRequest(message) && !message.getClass().getSimpleName().equals("ReqEcho")) {
//            logger.error("收到消息[{}]{}={}", getMessageSignure(session), message.getClass().getSimpleName());
        }
        Message msg = (Message) message;
        MessageStatistics.getInstance().addReceived(msg.getModule());
        nextFilter.messageReceived(session, message);
    }

    private boolean traceRequest(Object message) {
        Set<Class<?>> ignores = new HashSet<>();
        ignores.add(ReqMultiMoveTo.class);
        return !ignores.contains(message.getClass());
    }

    @Override
    public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
        Object message = writeRequest.getMessage();
        if (debug && traceResponse(message) && !message.getClass().getSimpleName().equals("RespReplyEcho")) {
            //log.error("发送消息[{}]{}={}", getMessageSignure(session), message.getClass().getSimpleName(), JSONObject.toJSONString(message));
        }

        Message msg = (Message) message;
        MessageStatistics.getInstance().addSent(msg.getModule());
        nextFilter.messageSent(session, writeRequest);
    }
    @Override
    public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
        //System.out.println("session关闭");
        nextFilter.sessionClosed(session);
    }
    @Override
    public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception {
        System.out.println("session等待");
        nextFilter.sessionIdle(session, status);
    }
    private boolean traceResponse(Object message) {
        Set<Class<?>> ignores = new HashSet<>();
        return !ignores.contains(message.getClass());
    }

    private String getMessageSignure(IoSession session) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role != null) {
            return role.getName();
        }
        return String.valueOf(session);
    }

}
